# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
from douban import settings


class DoubanPipeline(object):
    def __init__(self):
        self.connect = pymysql.connect(
            host=settings.MYSQL_HOST,
            db=settings.MYSQL_DBNAME,
            user=settings.MYSQL_USER,
            passwd=settings.MYSQL_PASSWD,
            port = settings.MYSQL_PORT,
            charset='utf8',
            use_unicode=True
        )
        self.cursor = self.connect.cursor()

    def process_item(self, item, spider):
        try:
            self.cursor.execute("""select * from app_movietop where detail = %s""", item['detail'])
            repetition = self.cursor.fetchone()
            if repetition:
                pass
            else:
                self.cursor.execute(
                    """insert into app_movietop(name,director,year,type,rating,rating_num,quote,detail) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)""",
                    (item['name'], item['director'], item['year'], item['type'], item['rating'],
                     item['rating_num'], item['quote'], item['detail'])
                )
            self.connect.commit()
        except Exception as error:
            print(error)
        return item
